import React from "react"
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import Cloud from "leancloud-storage"

function getBase64(img, callback) { //将Upload组件得到的本地图片,转化为base64编码
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

function beforeUpload(file) { //限制上传必须是图片 && 小于2M
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
}

class ImgUpload extends React.Component {
  state = {
    loading: false,
  };

  customRequest=(info)=>{
    // console.log("本地资源信息",info);
    getBase64(info.file,(imgstr)=>{
      // console.log("img的base64编码",imgstr);//imgstr就是获取到的base64编码字符串
      const data = { base64: imgstr };
      const file = new Cloud.File('pic.png', data);//构建可用于上传的file对象
      file.save().then((file) => {
        let imgUrl = file.attributes.url
        this.setState({
          imageUrl:imgUrl
        })
        this.props.getImgurl(imgUrl)
      }, (error) => {
        console.log(error);
        // 保存失败，可能是文件无法被读取，或者上传过程中出现问题
      });
    })
  };

  render() {
    const { loading, imageUrl } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        customRequest={this.customRequest}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    );
  }
}

export default ImgUpload;